﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

[AddComponentMenu("TagMachine/Gameplay/Wolf Picking At Start")]
public class WolfPickingAtStart : PauseSystem 
{
	public float GameStart 				= 3.0f;

	private PlayerEntity[] m_Players 	= null;
	private GameObject[] m_SpawnPoints 	= null;

	private Timer m_GameStartTimer 		= null;
	public float RemainingTime 			{ get { return m_GameStartTimer.RemainingTime; } }

	// Use this for initialization
	void Awake()
	{
		// Create timer
		m_GameStartTimer 				= gameObject.AddComponent< Timer >();
		m_GameStartTimer.StartOnAwake 	= true;
		m_GameStartTimer.DestroyOnEnd 	= false;
		m_GameStartTimer.RestartTimes	= 1;
		m_GameStartTimer.Duration 		= GameStart;
		m_GameStartTimer.TimerCallbackEvent += StartGame;

		m_ChangeEnableOnPause 			= false;
	}

	void RefreshPlayers()
	{		
		m_Players						= GameObject.FindObjectsOfType< PlayerEntity > ();
		Array.Sort( m_Players, (P1, P2) => 
			{ return P1.GetComponent< MovingEntity >().NumPlayer.CompareTo( P2.GetComponent< MovingEntity >().NumPlayer ); } );

		m_SpawnPoints					= GameObject.FindGameObjectsWithTag( GameModeClassic.Instance.SpawnPointTag );

		if ( m_Players.Length > m_SpawnPoints.Length )
		{
			Debug.LogWarning("Not enough spawn points!");
		}
	}

	public void Restart()
	{
		enabled = true;

		if ( m_Players == null || m_SpawnPoints == null )
		{
			RefreshPlayers();
		}

		Unpause();
		m_GameStartTimer.Restart();
		SetupPlayers ();
	}

	void SetupPlayers()
	{
		Tools.Shuffle( ref m_SpawnPoints );

		// Randomize their position
		for (int i = 0; i < m_Players.Length; ++i )
		{
			if ( i < m_SpawnPoints.Length )
			{
				m_Players[i].transform.position 	= m_SpawnPoints[i].transform.position;
			}
			m_Players[i].Reset();
		}

	}

	void StartGame() 
	{
		m_GameStartTimer.enabled 	= false;
		enabled 					= false;

		GameModeClassic.Instance.StartRound();
		
		for (int i = 0; i < m_Players.Length; ++i) 
		{
			m_Players[i].GetComponent< MovingEntity >().enabled = true;

			if ( i == GameModeClassic.Instance.CurrentRound ) 
			{
				GameModeClassic.Instance.SwitchWolf( m_Players[i] );
			}
			else
			{
				m_Players[i].SwitchToFugitive();
			}
		}

		Debug.Log("Game Starts with player " + GameModeClassic.Instance.CurrentRound + " as wolf!!!");
	}

	public override void Pause()
	{
		if ( enabled )
		{
			base.Pause();

			m_GameStartTimer.Pause();
		}
	}

	public override void Unpause()
	{
		if ( enabled )
		{
			base.Unpause();

			m_GameStartTimer.Unpause();
		}
	}
}
